const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const config = require('../config/config');
// 移除直接导入的模型，改用动态加载方式

const db = {};
const sequelize = new Sequelize(
  config.database.name,
  config.database.user,
  config.database.password,
  {
    host: config.database.host,
    port: config.database.port,
    dialect: config.database.dialect || 'mysql', // 确保提供方言
    pool: config.database.pool,
    logging: config.database.logging && console.log,
    define: {
      underscored: true, // 使用下划线命名法
      freezeTableName: true // 禁止自动复数表名
    }
  }
);

// 测试数据库连接方法
const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
    return true;
  } catch (error) {
    console.error('数据库连接失败:', error);
    throw error;
  }
};

// 读取当前目录下的所有模型文件并导入
fs.readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== 'index.js') && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    try {
      const modelPath = path.join(__dirname, file);
      console.log(`尝试加载模型文件: ${file}`);
      // 导入模型定义
      const modelExport = require(modelPath);
      let model;
      
      try {
        if (typeof modelExport === 'function') {
          // 如果是普通函数，直接调用
          model = modelExport(sequelize);
        } else if (modelExport && modelExport.default && typeof modelExport.default === 'function') {
          // 如果是ES模块导出
          model = modelExport.default(sequelize);
        } else if (modelExport.prototype && modelExport.prototype.constructor) {
          // 如果是ES6类，需要实例化
          model = new modelExport(sequelize);
        } else {
          // 直接使用导出对象
          model = modelExport;
        }
        
        if (model && model.name) {
          console.log(`已加载模型: ${model.name}`);
          db[model.name] = model;
        } else {
          console.log(`跳过模型文件 ${file}，未找到有效模型`);
        }
      } catch (modelError) {
        console.error(`加载模型 ${file} 时出错:`, modelError);
      }
    } catch (importError) {
      console.error(`导入模型文件 ${file} 时出错:`, importError);
    }
  });

// 设置模型之间的关联关系
Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    try {
      db[modelName].associate(db);
      console.log(`已建立模型关联: ${modelName}`);
    } catch (error) {
      console.error(`建立模型关联失败 ${modelName}:`, error);
    }
  }
});

// 同步数据库模型
const syncDatabase = async (force = false) => {
  try {
    await sequelize.sync({ force });
    console.log('数据库同步完成');
  } catch (error) {
    console.error('数据库同步失败:', error);
    throw error;
  }
};

db.sequelize = sequelize;
db.Sequelize = Sequelize;
db.syncDatabase = syncDatabase;
db.testConnection = testConnection;

module.exports = db; 